package com.dcc.inventory.interceptor;


import com.dcc.inventory.entity.User;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebFilter("/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.addHeader("X-Frame-Options","SAMEORIGIN");
        response.addHeader("X-XSS-Protection","1");
        response.addHeader("X-Content-Type-Options","nosniff");
        response.addHeader("Content-Security-Policy","default-src 'self';script-src 'self' * ;img-src 'self';object-src 'self';frame-src 'self'");
        //获取资源请求路径
        String uri = request.getRequestURI();
        if (uri.contains("/authLogin")||uri.contains("index.html") ||uri.contains("/searchAuth")|| uri.contains("/login.html")||uri.contains("/login") || uri.contains(".js") || uri.contains(".css") || uri.contains("controller") || uri.contains("navigation")) {
            //包含放行
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            //从session中获取user
            User user = (User) session.getAttribute("user");
            User index =(User) session.getAttribute("index_user");
            if (user != null || index != null) {
                //登录了放行
                filterChain.doFilter(servletRequest, servletResponse);
            }
            else if (uri.contains("login.html")){
                request.getRequestDispatcher("/inventory/login.html").forward(request, servletResponse);
            }

        }
    }

    @Override
    public void destroy() {

        Filter.super.destroy();
    }
}
